package dsk.demo.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import dsk.demo.common.utils.PageUtils;
import dsk.demo.product.dao.ProductDao;
import dsk.demo.product.dto.ModelQueryDto;
import dsk.demo.product.entity.ProductCarEntity;
import dsk.demo.product.entity.ProductRefEntity;
import dsk.demo.product.service.SearchService;
import dsk.demo.product.vo.ProductVo;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    ProductDao productDao;

    @Override
    public List<ProductVo> search(String foundString) {
        List<ProductVo> productEntities = productDao.searchByFoundString(foundString);
        productEntities.stream().forEach(item -> {
            item.dealReturnOemList();
        });
        return productEntities;
    }

    @Override
    public PageUtils searchByCarKeyWord(ModelQueryDto dto) {
        int pageNum = dto.getPageNum();
        dto.setPageNum((pageNum-1) * dto.getLimit());
        List<ProductVo> productEntities = productDao.searchByCarModel(dto);
        //限制返回的数据总量
        productEntities.stream().forEach(item -> {
            item.dealReturnOemList();
            item.setCarList(item.getCarList().subList(0,item.getCarList().size()>5? 5 : item.getCarList().size()));
            List<ProductCarEntity> collect = item.getCarList().stream().filter(car -> {
                return StrUtil.isNotBlank(car.getBrand()) || StrUtil.isNotBlank(car.getFullname());
            }).collect(Collectors.toList());
            item.setCarList(collect);
        });
        PageUtils pageUtils = new PageUtils(productEntities,productDao.countByCarModel(dto.getKeyWord(),
                dto.getCatalogId()),dto.getLimit(),pageNum);
        return pageUtils;
    }

    @Override
    public void quoteExport(ProductVo[] productVo, HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter();
//        String nextLine = String.valueOf((char) 10);
        String nextLine = "\n";

        writer.setColumnWidth(0,20);
        writer.setColumnWidth(1,20);
        writer.setColumnWidth(2,25);
        writer.setColumnWidth(3,25);
        writer.setColumnWidth(4,10);
        writer.setColumnWidth(5,10);
        writer.setColumnWidth(6,30);
        writer.setColumnWidth(7,30);
        writer.setColumnWidth(8,20);

        CellStyle cellStyle = writer.createCellStyle();
        cellStyle.setWrapText(true);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setTopBorderColor(IndexedColors.BLACK.index);
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.index);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setRightBorderColor(IndexedColors.BLACK.index);
        cellStyle.setBorderRight(BorderStyle.THIN);

        writer.setRowHeight(0,30);
        writer.writeCellValue(0,0,"本厂编号");
        writer.writeCellValue(1,0,"产品类型");
        writer.writeCellValue(2,0,"图片");
        writer.writeCellValue(3,0,"属性");
        writer.writeCellValue(4,0,"价格A");
        writer.writeCellValue(5,0,"价格B");
        writer.writeCellValue(6,0,"OEM号码");
        writer.writeCellValue(7,0,"适配车型");
        writer.writeCellValue(8,0,"客户编号");
        writer.setRowHeight(0,30);
        for (int i=0;i<productVo.length;i++) {
            ProductVo product = productVo[i];
            writer.writeCellValue(0,i+1,getDefault(product.getProductNo()));    //本厂编号
            writer.writeCellValue(1,i+1,getDefault(product.getCatalogName()));  //产品类型
            //2图片
            File fileFrom = getFileFrom(product.getImage());
            if (fileFrom.exists()) {
                writer.writeImg(fileFrom,2,i+1,3,i+2); //图片
            }
            writer.writeCellValue(3,i+1,getDefault(product.getAttributes())  + "\t");   //属性

            writer.writeCellValue(4,i+1,product.getPrice()==null?0:product.getPrice());        //价格A
            writer.writeCellValue(5,i+1,product.getPrice1()==null?0:product.getPrice1());       //价格B
            StringBuilder sb = new StringBuilder();
            if (product.getOemList()!=null) {
                for (ProductRefEntity productRefEntity : product.getOemList()) {
                    sb.append(productRefEntity.getBrand()).append(": ").append(productRefEntity.getRefNo()).append(nextLine);
                }
                writer.writeCellValue(6,i+1,sb.toString() + "\t");       //OEM号码
            }
            if (product.getCarList()!=null) {
                sb = new StringBuilder();
                for (ProductCarEntity car : product.getCarList()) {
                    sb.append(car.getBrand()).append(nextLine);
                }
                writer.writeCellValue(7,i+1,sb.toString() + "\t");       //适配车型
            }
            writer.setStyle(cellStyle, 3,i+1);
            writer.setStyle(cellStyle, 6,i+1);
            writer.setStyle(cellStyle, 7,i+1);

            writer.writeCellValue(8,i+1,getDefault(product.getCustomerNo())); //客户号码
            writer.setRowHeight(i+1,80);
        }

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename=temp.xls");
        writer.flush(response.getOutputStream(),true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(response.getOutputStream());
    }

    private static String baseFilePath = "mydata"+File.separator+"nginx"+File.separator+"html"+File.separator+"images"+File.separator;

    private File getFileFrom(String image){
        if (StrUtil.isBlank(image)) {
            return new File(File.separator + baseFilePath + "xxxx.png");
        }
        String[] images = image.split("images");
        return new File(File.separator + baseFilePath + images[1]);
    }

    private String getDefault(String str){
        if (str == null) {
            return "";
        }
        return str;
    }

    @Override
    public Map<String, List<ProductVo>> searchFoundStringList(List<String> foundStringList) {
        List<String> finalFoundStringList = foundStringList.stream().map(item -> {
            return dsk.demo.product.util.StrUtil.getFoundString(item);
        }).collect(Collectors.toList());

        List<ProductVo> productEntities = productDao.searchFoundStringList(finalFoundStringList);

        Map<String, List<ProductVo>> result = new HashMap<>();
        for (String foundString : foundStringList) {
            String finalFoundString = dsk.demo.product.util.StrUtil.getFoundString(foundString);
            Set<ProductVo> collect = productEntities.stream().filter(item -> {
                        for (ProductRefEntity productRefEntity : item.getOemList()) {
                            if (productRefEntity.getSearchProductNo().equals(finalFoundString)
                                    || productRefEntity.getSearchNo().equals(finalFoundString)) {
                                return true;
                            }
                        }
                        return false;
                    }
            ).collect(Collectors.toSet());
            List<ProductVo> newSet = BeanUtil.copyToList(collect, ProductVo.class);
            result.put(foundString,newSet);
        }
        return result;
    }


}
